<template>
  <div class="editorBox2" :id="'editorHover' + id">
    <div class="box">
      <div class="editorHoverBox">
        <div :id="'fatherTinydemo' + id" class="fatherTiny">
          <div :id="'tinydemo' + id" :class="'tinydemo' + id + ' css borderBlue'" :style="'height:' + height + 'px'">
          </div>
        </div>
        <div class="resize" :id="'tinyDown' + id" @mousedown="dragEagle">
          <div :id="'tinyDownDiv' + id" class="upDown">
            <svg t="1661841564832" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="8376" width="40" height="40">
              <path
                d="M192 448c10.9 0 21.8-4.2 30.2-12.5L497 160.8c5.4-5.4 11.8-6.2 15.1-6.2 3.3 0 9.6 0.8 15.1 6.2l274.7 274.7c16.7 16.7 43.7 16.7 60.3 0 16.7-16.7 16.7-43.7 0-60.3L587.4 100.4c-41.6-41.6-109.3-41.6-150.9 0L161.8 375.2c-16.7 16.7-16.7 43.7 0 60.3 8.4 8.3 19.3 12.5 30.2 12.5zM801.8 588.5L527.1 863.2c-5.4 5.4-11.8 6.2-15.1 6.2-3.3 0-9.7-0.8-15.1-6.2L222.2 588.5c-16.7-16.7-43.7-16.7-60.3 0-16.7 16.7-16.7 43.7 0 60.3l274.8 274.8c20.8 20.8 48.1 31.2 75.4 31.2 27.3 0 54.6-10.4 75.4-31.2l274.7-274.8c16.7-16.7 16.7-43.7 0-60.3-16.7-16.7-43.7-16.7-60.4 0z"
                fill="#BDBDBD" p-id="8377" />
            </svg>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import axios from 'axios';
import { ref, onUnmounted, onBeforeMount, onBeforeUnmount, getCurrentInstance, toRefs, reactive } from "vue";
import { showLoading, hideLoding } from "../../../utils/paper.js";
import "../../../tinymce/tinymce";
import "../../../tinymce/themes/silver/theme";
import "../../../tinymce/icons/default/icons";
import "../../../tinymce/plugins/link";
import "../../../tinymce/plugins/code";
import "../../../tinymce/plugins/table";
import "../../../tinymce/plugins/lists";
import "../../../tinymce/plugins/contextmenu";
import "../../../tinymce/plugins/wordcount";
import "../../../tinymce/plugins/colorpicker";
import "../../../tinymce/plugins/textcolor";
import "../../../tinymce/plugins/image";
import "../../../tinymce/plugins/media";
import "../../../tinymce/plugins/autoresize";
import "../../../tinymce/plugins/paste";
import { ElLoading } from "element-plus";
const { proxy, ctx } = getCurrentInstance();
import { getToken, setTop } from "../../../utils/auth.js";
import { onMounted } from "vue-demi";
const emit = defineEmits(["update:modelValue", 'getId']);
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  subjectContentPreview: {
    type: String,
    default: "",
  },
  height: {
    type: [String, Number],
    default: 200,
  },
  focus: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  //默认插件 选择你需要的 注释掉的为富文本全部默认插件
  plugins: {
    type: [String, Array],
    default:
      // "preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr nonbreaking insertdatetime advlist lists wordcount imagetools textpattern autosave bdmap autoresize lineheight"
      "paste autoresize media link code table lists wordcount image kityformula_editor mathjax",
  },
  //默认工具栏 选择你需要的 注释掉的为富文本全部默认工具
  toolbar: {
    type: [String, Array],
    default:
      "pastetext restoreText clearHTML code bold italic underline bullist numlist subscript superscript outdent indent  | alignleft aligncenter alignright |charmap tiny_mce_wiris_formulaEditor tiny_mce_wiris_formulaEditorChemistry kityformula_editor mathjax image media| fontselect  | fontsizeselect",
    // "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link codesample | alignleft aligncenter alignright alignjustify outdent indent lineheight formatpainter | \
    // styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    // table image media charmap hr pagebreak insertdatetime | bdmap fullscreen preview"
  },
});
const { id, tinymceContent, uploaded, resVideo } = toRefs(
  reactive({
    id: (Math.random() * 1000).toFixed(0) + "", //为每个组件创建不同的id
    resVideo: "",
    uploaded: false,
  })
);
const svg = ref(`
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `);
const url = ref(localStorage.getItem('tinymceUrl'));
onBeforeMount(() => { });
onMounted(() => {
  showLoading();
  tinymce.init({
    selector: ".tinydemo" + id.value,
    language_url: "/static/tinymce/langs/zh_CN.js",
    language: "zh_CN",
    directionality: "ltr",
    skin_url: "/static/tinymce/skins/ui/oxide",
    content_css: "/static/tinymce/skins/content/document/content.css",
    external_plugins: {
      tiny_mce_wiris: "/static/tinymce/plugins/tiny_mce_wiris/plugin.js",
      kityformula_editor:
        "/static/tinymce/plugins/kityformula-editor/plugin.js",
      mathjax: "/static/tinymce/plugins/tinymce-mathjax/plugin.js",
    },
    mathjax: {
      lib: "/static/tinymce/plugins/tinymce-mathjax/mathjax/es5/tex-mml-chtml.js",
    },
    convert_urls: false,
    fixed_toolbar_container: '#EditTinId',
    toolbar_sticky: false,
    images_reuse_filename: true,
    height: props.height,
    min_height: props.height,
    paste_as_text: true,
    // max_height: props.height,
    toolbar_mode: "scrolling ",
    plugins: props.plugins,
    toolbar: props.toolbar,
    file_picker_types: "media",
    inline: true,
    force_br_newlines: true,
    force_p_newlines: false,
    forced_root_block: false,
    // auto_focus: true,
    content_style: "p {margin: 5px 0;}",
    object_resizing: true, // 图片和表格是否开启在编辑器内部缩放
    paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
    fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
    font_formats:
      "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;Symbol字体=symbol;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
    branding: false,
    contextmenu: "undo redo | cut copy paste pastetext | selectall table", // 富文本右键菜单
    init_instance_callback: (editor) => {
      let text = JSON.parse(JSON.stringify(props.modelValue))
      // text = text.replace(/src="ct-api-online/g, 'src="https://ct.hep.com.cn/ct-api-online')
      // text = text.replace(/src=\"fileFolder\/kindeditor/g, 'src="https://ct.hep.com.cn/ct-api-online/fileFolder/kindeditor')
      // text = text.replace(/src=\"\.\.\/fileFolder\/kindeditor/g, 'src="https://ct.hep.com.cn/ct-api-online/fileFolder/kindeditor')
      text = text.replace(/(\<math[^>]+) display="block"/g, '$1')
      const regex = /\$(.*?)\$/g;
      text = text.replace(regex, '<span class="math-tex">\\($1\\)</span>');
      tinymce.activeEditor.setContent(text.replace(/mml:/g, ""));
      emit("update:modelValue", tinymce.activeEditor.getContent());
      if (!props.tiankong) {
        editor.on("input", (e) => {
          emit("update:modelValue", tinymce.activeEditor.getContent());
        });
        editor.on("blur", (e) => {
          emit("update:modelValue", tinymce.activeEditor.getContent());
          if (document.getElementById("fatherTinydemo" + id.value)) {
            document
              .getElementById("fatherTinydemo" + id.value)
              .style.setProperty("margin", "0");
          }
          if (document.getElementById("editorHover" + id.value)) {
            document
              .getElementById("editorHover" + id.value)
              .style.setProperty("border", "#dcdfe6 1px solid");
          }
        });
        editor.on("focus", (e) => {
          document
            .getElementById("editorHover" + id.value)
            .style.setProperty("border", "#488cfb 1px solid");
          let array = document.getElementsByClassName("tox-tinymce");
          for (let index = 0; index < array.length; index++) {
            document
              .getElementsByClassName("tox-tinymce")
            [index].style.setProperty(
              "top",
              getElementTop(document.querySelector("#tinydemo" + id.value)) -
              80 +
              "px"
            );
            document
              .getElementsByClassName("tox-tinymce")
            [index].style.setProperty(
              "width",
              document.querySelector("#tinydemo" + id.value).offsetWidth +
              "px"
            );
          }
          setTop()
        });
        editor.on("ExecCommand", (e) => {
          emit("update:modelValue", tinymce.activeEditor.getContent());
        });
      }
    },
    setup: (editor) => {
      editor.ui.registry.addButton("clearHTML", {
        icon: "format-painter",
        tooltip: "清除HTML代码",
        onAction: () => {
          tinymce.activeEditor.setContent(
            tinymce.activeEditor
              .getContent({ format: "text" })
              .replace(/&nbsp;/g, "")
          );
          emit("update:modelValue", tinymce.activeEditor.getContent());
        },
      });
      // editor.ui.registry.addButton("restoreText", {
      //   icon: "preview",
      //   tooltip: "源代码",
      //   onAction: () => {
      //      tinymce.activeEditor.setContent(props.subjectContentPreview)
      //   },
      // });
    },
    paste_preprocess: function (pl, o) {
      // 粘贴过滤
      var str = o.content;
      var ta = document.createElement("textarea");
      ta.innerHTML = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
      const regex = /\$(.*?)\$/g;
      const output = ta.value.replace(regex, '<span class="math-tex">\\($1\\)</span>');
      o.content = output;
    },
    images_upload_handler: function (blobInfo, succFun, failFun, progress) {
      var xhr, formData;
      var file = blobInfo.blob(); //转化为易于理解的file对象
      if (file.size > 5242880) return failFun("图片大小不能超过5M");
      if (!["image/jpeg", "image/png", "image/gif"].includes(file.type))
        return failFun("只能上传JPG、PNG、GIF图片");
      xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open("POST", url.value);
      xhr.setRequestHeader("Authorization", "Bearer " + getToken());
      xhr.onload = function () {
        var json = JSON.parse(xhr.responseText);
        if (json.code != 200) {
          failFun("HTTP Error: " + json.error);
          return;
        }
        succFun(localStorage.getItem('domainName') + json.path, { alt: "文件" });
      };
      formData = new FormData();
      formData.append("file", file, file.name); //此处与源文档不一样
      xhr.send(formData);
    },
    file_picker_callback: async (callback, value, meta) => {
      if (meta.filetype == "media") {
        let input = document.createElement("input"); //创建一个隐藏的input
        input.setAttribute("type", "file");
        input.onchange = function async() {
          const loading = ElLoading.service({
            lock: true,
            text: "编辑器加载中...",
            background: "rgba(255, 255, 255, 0.7)",
          });
          let file = this.files[0]; //选取第一个文件
          var xhr, formData;
          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open("POST", url.value);
          xhr.setRequestHeader("Authorization", "Bearer " + getToken());
          xhr.onload = function () {
            var json = JSON.parse(xhr.responseText);
            if (json.code != 200) {
              proxy.Message.error("HTTP Error: " + json.msg);
              return;
            }
            resVideo.value = localStorage.getItem('domainName') + json.path;
            callback(resVideo.value, { title: file.name });
            loading.close();
          };
          formData = new FormData();
          formData.append("file", file, file.name); //此处与源文档不一样
          xhr.send(formData);
        };
        //触发点击
        input.click();
      }
    },
  });
  setTimeout(() => {
    hideLoding();
  }, 5000);
});
function getElementTop(elem) {
  var elemTop = elem.offsetTop; //获得elem元素距相对定位的父元素的top

  elem = elem.offsetParent; //将elem换成起相对定位的父元素

  while (elem != null) {
    //只要还有相对定位的父元素

    //获得父元素 距他父元素的top值,累加到结果中

    elemTop += elem.offsetTop; //再次将elem换成他相对定位的父元素上;

    elem = elem.offsetParent;
  }

  return elemTop;
}
function dragEagle(e) {
  //鼠标拖动改变div大小
  var targetDiv = document.getElementsByClassName("tinydemo" + id.value);
  //得到点击时该地图容器的宽高：
  var targetDivHeight = targetDiv[0].offsetHeight;
  var startX = e.clientX;
  var startY = e.clientY;
  document.onmousemove = function (e) {
    e.preventDefault();
    //得到鼠标拖动的宽高距离：取绝对值
    var distX = Math.abs(e.clientX - startX);
    var distY = Math.abs(e.clientY - startY);
    //往下方拖动：
    if (e.clientY > startY) {
      targetDiv[0].style.height = targetDivHeight + distY + "px";
    }
    //往上方拖动：
    if (e.clientY < startY) {
      targetDiv[0].style.height = targetDivHeight - distY + "px";
    }
    if (parseInt(targetDiv[0].style.height) >= 700) {
      targetDiv[0].style.height = 700 + "px";
    }
    if (parseInt(targetDiv[0].style.height) <= props.height) {
      targetDiv[0].style.height = props.height + "px";
    }
  };
  document.onmouseup = function () {
    document.onmousemove = null;
  };
}
onBeforeUnmount(() => {
  tinymce.remove();
});


</script>



<style scoped lang="scss">
.box {
  position: relative;
  background: #fff;
  margin-bottom: 6px;
}

.css {
  width: 100%;
  border-radius: 4px;
  text-align: left;
  overflow: auto;
  position: relative;
}

.resize {
  width: 100%;
  height: 15px;
  cursor: n-resize;
  position: absolute;
  bottom: -6px;
  left: 0;
  background: #fafafa;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upDown svg {
  width: 15px;
  height: 13px;
}

.resize div {
  // width: 16px;
  // height: 3px;
  // border-radius: 2px;
  // background: rgb(187, 186, 186);
}

.tox {
  position: absolute !important;
  top: 20px !important;
  display: block !important;
}

body .tox-tinymce-inline {
  top: 594px !important;
  left: 272px !important;
  visibility: inherit !important;
  display: block !important;
  z-index: 99999;
}
</style>